import java.util.Scanner;

public class Main {
    /**
     * 左旋转字符串
     * https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
     * 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作
     * 的功能。比如，输入字符串"abcdefg"和数字2，该函数将返回左旋转两位得到的结果"cdefgab"。
     */
    public static void main(String[] args) {
        System.out.println("hello world 0_<");
        Scanner scanner = new Scanner(System.in);
        System.out.println("s：");
        String s = scanner.nextLine();
        System.out.println("k：");
        int k = scanner.nextInt();
        System.out.println(new Main().reverseLeftWords(s, k));
    }
    public String reverseLeftWords(String s, int n) {
        // 使用数组速度快
        // 局部反转之后整体反转 abcdefg -> bagfedc -> cdefgab
        char[] chars = s.toCharArray();
        // 两部分局部反转
        int left = 0, right = n - 1;
        while (left < right) {
            chars[left] ^= chars[right];
            chars[right] ^= chars[left];
            chars[left] ^= chars[right];
            left++;
            right--;
        }
        left = n; right = chars.length - 1;
        while (left < right) {
            chars[left] ^= chars[right];
            chars[right] ^= chars[left];
            chars[left] ^= chars[right];
            left++;
            right--;
        }
        // 整体反转
        left = 0; right = chars.length - 1;
        while (left < right) {
            chars[left] ^= chars[right];
            chars[right] ^= chars[left];
            chars[left] ^= chars[right];
            left++;
            right--;
        }
        return new String(chars);
    }
    public String reverseLeftWords2(String s, int n) {
        // 局部反转之后整体反转 abcdefg -> bagfedc -> cdefgab
        StringBuilder stringBuilder = new StringBuilder(s);
        int left = 0, right = n - 1;
        // 两部分局部反转
        while (left < right) {
            char temp = stringBuilder.charAt(left);
            stringBuilder.setCharAt(left++, stringBuilder.charAt(right));
            stringBuilder.setCharAt(right--, temp);
        }
        left = n; right = stringBuilder.length() - 1;
        while (left < right) {
            char temp = stringBuilder.charAt(left);
            stringBuilder.setCharAt(left++, stringBuilder.charAt(right));
            stringBuilder.setCharAt(right--, temp);
        }
        // 整体反转
        left = 0; right = stringBuilder.length() - 1;
        while (left < right) {
            char temp = stringBuilder.charAt(left);
            stringBuilder.setCharAt(left++, stringBuilder.charAt(right));
            stringBuilder.setCharAt(right--, temp);
        }
        return stringBuilder.toString();
    }
}
